package com.hejun.security.config;

import com.hejun.security.filter.ValidCodeFilter;
import com.hejun.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class SecurityConfig implements WebMvcConfigurer {

    @Autowired
    UserService userService;

    @Autowired
    ValidCodeFilter validCodeFilter;
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();//加盐加密   md5  e10xxxxx
        //如果不想加密就返回
//        return NoOpPasswordEncoder.getInstance();
    }

    //静态资源放行白名单
    @Bean
    WebSecurityCustomizer webSecurityCustomizer(){
        return web -> web.ignoring().requestMatchers(
                "/css/**","/js/**","/static/**","/webjars/**");
    }

    //过滤器链条放行白名单
    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity security) throws Exception {

        security.authorizeRequests().requestMatchers("/index","/toLogin","/validcode").permitAll()//匿名访问
                .requestMatchers("/level1/**").hasRole("role1")
                .requestMatchers("/level2/**").hasRole("role2")
                .requestMatchers("/level3/**").hasRole("role3")
                .anyRequest().authenticated()//其余所有需要认证
                .and().formLogin().loginPage("/toLogin")//自定义登录页
                .loginProcessingUrl("/login") //login表达提交到哪儿
                .defaultSuccessUrl("/",true) //登陆成功后跳转到哪儿.
                .and().logout().logoutSuccessUrl("/")//注销后默认跳哪儿
                .and().userDetailsService(userService)//代替了之前写死的用户
                .csrf().disable()
                .rememberMe()//开启记住我功能
                .and().addFilterBefore(validCodeFilter, UsernamePasswordAuthenticationFilter.class);//添加验证码校验在·

        return security.build();
    }

}